package com.tang.script.functions;

import com.tang.script.command.AbstractScriptCommand;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;

import javax.script.Bindings;
import java.util.List;

public class FunctionsLinker {
    private final static FunctionsLinker functionsLinker = new FunctionsLinker();

    public static FunctionsLinker get() {
        return functionsLinker;
    }

    public void linkFunctions(AbstractScriptCommand command) {
        List<String> functions = command.getFunctions();
        //定义方法
        Bindings binding = command.getBinding();
        for (String function : functions) {
            defFunction(function,  command);
        }
    }

    private void defFunction(String function,  AbstractScriptCommand command) {
        Object fun = command.getScriptEngine().loadFunction(function);
        Bindings binding = command.getBinding();
        binding.put(function, fun);
    }
}
